import * as mockjs from 'mockjs';
import * as CryptoJS from 'crypto-js';
import * as moment from 'moment';

const IHelper = new (class {
  sleep(milliseconds: number): Promise<number> {
    return new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(1);
      }, milliseconds);
    });
  }

  hash(len?: number, option?: { mixed?: boolean }): string {
    const length: number = len ? len : 6;
    const lower: string = 'abcdefghighlmnopqrstuvwxyz';
    const upper: string = lower.toUpperCase();
    const number: string = '0123456789';
    const symbol: string = '!@?$%^&*';
    const pool: string = `${number}${upper}${lower}${option?.mixed ? symbol : ''}`;
    return (
      mockjs.Random.string(lower, 1) + mockjs.Random.string(pool, length - 1)
    );
  }

  md5(l: string): string {
    return CryptoJS.MD5(l).toString();
  }

  unix(): number {
    return moment().unix();
  }

  convertToQueryString(params: object, ignoreEncode?: boolean): string {
    return Object.keys(params)
      .map(
        (k) =>
          `${k}=${ignoreEncode ? params[k] : encodeURIComponent(params[k])}`,
      )
      .join('&');
  }

  parseQueryStr(queryStr: string): { [prop: string]: string } {
    const obj: { [prop: string]: string } = {};
    queryStr.split('&').forEach((e) => {
      const [k, v] = e.split('=');
      obj[k] = decodeURIComponent(v);
    });
    return obj;
  }

  timeFormatted(format?: string) {
    return moment().format(format || 'YYYY-MM-DD HH:mm:ss');
  }

  getArray(len: number): number[] {
    return Array.from(new Array(len).keys());
  }
})();

export default IHelper;
